package com.nowcoder.community.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 韩
 * @version 1.0
 * 调用service方法的日志切面
 */
//@Component
//@Aspect
public class ServiceLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    //对service下的所有方法都进行日志记录
    @Pointcut("execution(* com.nowcoder.community.service.*.*(..))")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        //日志记录用户[1.2.3.4]，在[xxx]访问了[com.xxxx.service.xxx()].

        //获取request对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {//消费者调用了service，请求可能为null先不做处理
            return;
        }

        HttpServletRequest request = attributes.getRequest();

        String ip = request.getRemoteHost();//获取访问对象的ip
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());//获取当前时间
        //获取调用方法的全类名和方法名
        String target = joinPoint.getSignature().getDeclaringType() + "." + joinPoint.getSignature().getName();

        logger.info(String.format("用户[%s],在[%s]访问了[%s]。", ip, now, target));
    }
}
